package MultiChat;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatServer {
	public static final int port = 30030; //[ek] TODO use convention for static final variables: PORT
	public static int id = 0; //[ek] TODO same

	//public static Map <String, Socket> connections = new  HashMap <String, Socket>();
	
	//[DF] XXX: public?! �� ���� ������ ������ ������ � ����� �������� ������, ����� ���� �������� �������������.
	//[DF] ������ ��� ��� ��������, � ��� ������, ��� � �������...

	//[ek] XXX why List? why not Set or Map ?
	public static ArrayList<ChatThread> connections = new ArrayList<ChatThread>();
	//public static ArrayList<Socket> sockets = new ArrayList<Socket>();
	
	//[ek] TODO remove dead code
	public ChatServer() {
	}
	
	private void execute() {
		ExecutorService executorService = Executors.newCachedThreadPool(); //[ek] XXX overkill?
		
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(ChatServer.port);
			log("Server started");
			
			while(true) {
				Socket socket = serverSocket.accept();
				executorService.submit(new ChatThread (this, socket, ChatServer.id));
				log(socket.getInetAddress().getHostAddress());
				ChatServer.id++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (executorService != null) {
				executorService.shutdown();
			}
		}
		
	}

	public static void main(String[] arg) {
		ChatServer chatServer = new ChatServer();
		chatServer.execute();
	}

	public synchronized void log(String string) {
		System.out.println(new Date ().toString() + ": " + string);
	}
}
